// 个人中心页面初始化与逻辑
window.initProfilePage = function initProfilePage() {
    const editProfileBtn = document.getElementById('editProfileBtn');
    const saveProfileBtn = document.getElementById('saveProfileBtn');
    const cancelEditBtn = document.getElementById('cancelEditBtn');
    const avatarInput = document.getElementById('avatarInput');
    const resumeInput = document.getElementById('resumeInput');
    const removeResumeBtn = document.getElementById('removeResume');
    
    let originalFormData = {};
    
    // 页面加载时获取简历信息
    loadResumeInfo();
    
    // 编辑个人信息
    if (editProfileBtn) {
        editProfileBtn.addEventListener('click', function() {
            enableFormEditing();
        });
    }
    
    // 保存个人信息
    if (saveProfileBtn) {
        saveProfileBtn.addEventListener('click', function() {
            saveProfile();
        });
    }
    
    // 取消编辑
    if (cancelEditBtn) {
        cancelEditBtn.addEventListener('click', function() {
            cancelEditing();
        });
    }
    
    // 头像上传
    if (avatarInput) {
        avatarInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                uploadAvatar(file);
            }
        });
    }
    
    // 简历上传
    if (resumeInput) {
        resumeInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                handleResumeUpload(file);
            }
        });
    }
    
    // 拖拽上传功能
    const resumeUpload = document.getElementById('resumeUpload');
    if (resumeUpload) {
        // 点击上传区域触发文件选择
        resumeUpload.addEventListener('click', function() {
            resumeInput.click();
        });
        
        // 拖拽事件
        resumeUpload.addEventListener('dragover', function(e) {
            e.preventDefault();
            resumeUpload.classList.add('drag-over');
        });
        
        resumeUpload.addEventListener('dragleave', function(e) {
            e.preventDefault();
            resumeUpload.classList.remove('drag-over');
        });
        
        resumeUpload.addEventListener('drop', function(e) {
            e.preventDefault();
            resumeUpload.classList.remove('drag-over');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleResumeUpload(files[0]);
            }
        });
    }
    
    // 删除简历
    if (removeResumeBtn) {
        removeResumeBtn.addEventListener('click', function() {
            // 添加点击效果
            this.style.transform = 'scale(0.95)';
            setTimeout(() => {
                this.style.transform = '';
            }, 150);
            
            removeResume();
        });
    }
    
    // 启用表单编辑
    function enableFormEditing() {
        const formInputs = document.querySelectorAll('.form-input');
        
        // 保存原始数据
        formInputs.forEach(input => {
            if (input.id) {
                originalFormData[input.id] = input.value;
            }
        });
        
        // 启用输入框（除了学号）
        formInputs.forEach(input => {
            if (input.hasAttribute('id')) { // 只有有ID的输入框才能编辑，学号没有ID
                input.removeAttribute('readonly');
                input.style.background = '#FFFFFF';
            }
        });
        
        // 显示保存和取消按钮
        if (editProfileBtn) editProfileBtn.style.display = 'none';
        if (saveProfileBtn) saveProfileBtn.style.display = 'flex';
        if (cancelEditBtn) cancelEditBtn.style.display = 'block';
    }
    
    // 保存个人信息
    function saveProfile() {
        const formData = {
            name: document.getElementById('nameInput')?.value,
            phone: document.getElementById('phoneInput')?.value,
            college: document.getElementById('collegeInput')?.value,
            major: document.getElementById('majorInput')?.value,
            grade: parseInt(document.getElementById('gradeInput')?.value),
            profile: document.getElementById('profileInput')?.value
        };
        
        fetch('/api/user/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                disableFormEditing();
                showMessage('个人信息更新成功！', 'success');
            } else {
                showMessage('更新失败，请重试。', 'error');
            }
        })
        .catch(error => {
            showMessage('更新失败，请重试。', 'error');
        });
    }
    
    // 取消编辑
    function cancelEditing() {
        const formInputs = document.querySelectorAll('.form-input:not([readonly])');
        
        // 恢复原始数据
        formInputs.forEach(input => {
            if (originalFormData[input.id]) {
                input.value = originalFormData[input.id];
            }
        });
        
        disableFormEditing();
    }
    
    // 禁用表单编辑
    function disableFormEditing() {
        const formInputs = document.querySelectorAll('.form-input');
        
        // 禁用输入框
        formInputs.forEach(input => {
            input.setAttribute('readonly', true);
            input.style.background = '#F9FAFB';
        });
        
        // 隐藏保存和取消按钮
        if (editProfileBtn) editProfileBtn.style.display = 'flex';
        if (saveProfileBtn) saveProfileBtn.style.display = 'none';
        if (cancelEditBtn) cancelEditBtn.style.display = 'none';
    }
    
    // 上传头像
    function uploadAvatar(file) {
        const formData = new FormData();
        formData.append('avatar', file);
        
        fetch('/api/user/avatar', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新头像显示
                const avatarImg = document.querySelector('.avatar-image');
                if (avatarImg) {
                    avatarImg.src = `/static/${data.avatar_url}`;
                }
                showMessage('头像上传成功！', 'success');
            } else {
                showMessage('头像上传失败，请重试。', 'error');
            }
        })
        .catch(error => {
            showMessage('头像上传失败，请重试。', 'error');
        });
    }
    
    // 处理简历上传
    function handleResumeUpload(file) {
        // 验证文件类型
        if (!file.name.toLowerCase().endsWith('.pdf')) {
            showMessage('只支持PDF格式文件', 'error');
            return;
        }
        
        // 验证文件大小（10MB）
        if (file.size > 10 * 1024 * 1024) {
            showMessage('文件大小不能超过10MB', 'error');
            return;
        }
        
        // 显示上传进度
        const resumeInfo = document.getElementById('resumeInfo');
        const resumeUpload = document.getElementById('resumeUpload');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        
        if (resumeInfo && resumeUpload && fileName && fileSize) {
            fileName.textContent = file.name;
            fileSize.textContent = formatFileSize(file.size);
            
            resumeUpload.style.display = 'none';
            resumeInfo.style.display = 'block';
        }
        
        // 上传文件到服务器
        uploadResume(file);
    }
    
    // 上传简历到服务器
    function uploadResume(file) {
        const formData = new FormData();
        formData.append('resume', file);
        
        // 显示上传中状态
        const removeBtn = document.getElementById('removeResume');
        if (removeBtn) {
            removeBtn.innerHTML = '<iconify-icon icon="material-symbols:loading" width="16"></iconify-icon>';
            removeBtn.disabled = true;
        }
        
        fetch('/api/user/resume', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage('简历上传成功！', 'success');
                // 更新简历信息显示
                updateResumeDisplay(data.resume);
            } else {
                showMessage(data.error || '上传失败，请重试', 'error');
                // 恢复上传区域显示
                const resumeInfo = document.getElementById('resumeInfo');
                const resumeUpload = document.getElementById('resumeUpload');
                if (resumeInfo && resumeUpload) {
                    resumeInfo.style.display = 'none';
                    resumeUpload.style.display = 'block';
                }
            }
        })
        .catch(error => {
            console.error('上传简历错误:', error);
            showMessage('上传失败，请重试', 'error');
            // 恢复上传区域显示
            const resumeInfo = document.getElementById('resumeInfo');
            const resumeUpload = document.getElementById('resumeUpload');
            if (resumeInfo && resumeUpload) {
                resumeInfo.style.display = 'none';
                resumeUpload.style.display = 'block';
            }
        })
        .finally(() => {
            // 恢复删除按钮状态
            const removeBtn = document.getElementById('removeResume');
            if (removeBtn) {
                removeBtn.innerHTML = '<iconify-icon icon="material-symbols:delete" width="16"></iconify-icon>';
                removeBtn.disabled = false;
            }
        });
    }
    
    // 删除简历
    function removeResume() {
        // 使用更友好的确认对话框
        const confirmMessage = '确定要删除当前简历吗？\n\n删除后将无法恢复，需要重新上传。';
        if (confirm(confirmMessage)) {
            // 显示删除中状态
            const removeBtn = document.getElementById('removeResume');
            if (removeBtn) {
                removeBtn.classList.add('loading');
                removeBtn.innerHTML = '<iconify-icon icon="material-symbols:loading" width="18"></iconify-icon> 删除中...';
                removeBtn.disabled = true;
            }
            
            fetch('/api/user/resume', {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('简历删除成功！', 'success');
                    // 恢复上传区域显示
                    const resumeInfo = document.getElementById('resumeInfo');
                    const resumeUpload = document.getElementById('resumeUpload');
                    const resumeInput = document.getElementById('resumeInput');
                    
                    if (resumeInfo && resumeUpload && resumeInput) {
                        resumeInfo.style.display = 'none';
                        resumeUpload.style.display = 'block';
                        resumeInput.value = '';
                    }
                } else {
                    showMessage(data.error || '删除失败，请重试', 'error');
                }
            })
            .catch(error => {
                console.error('删除简历错误:', error);
                showMessage('删除失败，请重试', 'error');
            })
            .finally(() => {
                // 恢复删除按钮状态
                const removeBtn = document.getElementById('removeResume');
                if (removeBtn) {
                    removeBtn.classList.remove('loading');
                    removeBtn.innerHTML = '<iconify-icon icon="material-symbols:delete" width="18"></iconify-icon> 删除';
                    removeBtn.disabled = false;
                }
            });
        }
    }
    
    // 更新简历显示
    function updateResumeDisplay(resume) {
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        
        if (fileName && fileSize && resume) {
            fileName.textContent = resume.file_name;
            fileSize.textContent = `${resume.file_size} MB`;
            
            // 添加过期时间显示
            const expiryDate = new Date(resume.expiry_date);
            const now = new Date();
            const daysLeft = Math.ceil((expiryDate - now) / (1000 * 60 * 60 * 24));
            
            const fileSizeElement = document.querySelector('.file-size');
            if (fileSizeElement) {
                fileSizeElement.innerHTML = `
                    文件大小: <span id="fileSize">${resume.file_size} MB</span>
                    <br>
                    <small style="color: ${daysLeft <= 3 ? '#dc2626' : '#6b7280'};">
                        剩余时间: ${daysLeft} 天
                    </small>
                `;
            }
        }
    }
    
    // 加载简历信息
    function loadResumeInfo() {
        fetch('/api/user/resume', {
            method: 'GET'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.resume) {
                // 显示简历信息
                const resumeInfo = document.getElementById('resumeInfo');
                const resumeUpload = document.getElementById('resumeUpload');
                
                if (resumeInfo && resumeUpload) {
                    resumeUpload.style.display = 'none';
                    resumeInfo.style.display = 'block';
                    updateResumeDisplay(data.resume);
                }
            } else {
                // 显示上传区域
                const resumeInfo = document.getElementById('resumeInfo');
                const resumeUpload = document.getElementById('resumeUpload');
                
                if (resumeInfo && resumeUpload) {
                    resumeInfo.style.display = 'none';
                    resumeUpload.style.display = 'block';
                }
            }
        })
        .catch(error => {
            console.error('获取简历信息错误:', error);
        });
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
    
    // 显示消息
    function showMessage(message, type) {
        // 创建消息元素
        const messageDiv = document.createElement('div');
        messageDiv.className = `message-toast ${type}`;
        messageDiv.textContent = message;
        
        // 添加到页面
        document.body.appendChild(messageDiv);
        
        // 显示动画
        setTimeout(() => {
            messageDiv.classList.add('show');
        }, 100);
        
        // 自动隐藏
        setTimeout(() => {
            messageDiv.classList.remove('show');
            setTimeout(() => {
                document.body.removeChild(messageDiv);
            }, 300);
        }, 3000);
    }
};


